"""示例运行脚本：加载数据，运行回测并保存结果"""
import os
import pandas as pd
from .backtester import run_backtest, compute_metrics
from .viz import plot_results


def main(data_path: str, out_dir: str):
    os.makedirs(out_dir, exist_ok=True)
    df = pd.read_csv(data_path)
    params = {
        'macd_fast': 12,
        'macd_slow': 26,
        'macd_signal': 9,
        'rsi_period': 14,
        'ma_short': 20,
        'ma_long': 50,
        'atr_period': 14,
        'entry_threshold': 0.5,
        'exit_threshold': 0.0,
        'w_macd': 0.4,
        'w_rsi': 0.2,
        'w_ma': 0.2,
        'w_vol': 0.2,
        'commission': 0.0005,
        'stamp_tax': 0.001,
        'base_slippage': 0.0002,
        'slippage_coef': 1e5,
        'risk_per_trade': 0.01,
        'stop_atr_mult': 2.0,
        'take_atr_mult': 4.0
    }
    results = run_backtest(df, params, initial_capital=1_000_000)
    metrics = compute_metrics(results['equity_curve'], results['trades'], 1_000_000)
    print('metrics:', metrics)
    # save trades
    trades_path = os.path.join(out_dir, 'trades.csv')
    results['trades'].to_csv(trades_path, index=False)
    # plot
    fig = plot_results(df, results['equity_curve'], results['trades'], savepath=os.path.join(out_dir, 'report.png'))
    print('saved', trades_path)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--data', required=True, help='path to stock csv')
    parser.add_argument('--out', required=True, help='output dir')
    args = parser.parse_args()
    main(args.data, args.out)
